package com.plentitude.easytrader.ui;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.plentitude.easytrader.R;
import com.plentitude.easytrader.provider.WatchlistContract.Data;
import com.plentitude.easytrader.provider.WatchlistContract.Quotes;
import com.plentitude.easytrader.provider.WatchlistDatabase.Tables;
import com.plentitude.easytrader.util.CustomProgressDialog;
import com.plentitude.easytrader.util.NotifyingAsyncQueryHandler;
import com.plentitude.easytrader.util.NotifyingAsyncQueryHandler.AsyncQueryListener;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AlphabetIndexer;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;


/**
 * Watchlist page.
 * 
 * @author team@getstarted.com.ua
 */
public class WatchlistActivity extends ListActivity  implements AsyncQueryListener {
	private String TAG = "WatchlistActivity";
	public static CursorAdapter mAdapter;
	private NotifyingAsyncQueryHandler mHandler;
	private String filter;
	private AutoCompleteTextView edtSearch;
	private ArrayAdapter<String> searchAdapter;
	private CustomProgressDialog progressDialog;
	
	private ImageView icForex;
	private ImageView icCommodities;
	private ImageView icStocks;
	private ImageView icHeld;
	private ImageView icActive;
	private ImageView icAllItems;
	
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.activity_watchlist);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
        
        mAdapter = new WatchlistAdapter(this);
        setListAdapter(mAdapter);
        edtSearch = (AutoCompleteTextView) findViewById(R.id.edtSearch);
        
        LinearLayout timestamp = (LinearLayout) findViewById(R.id.timestamp);
        timestamp.setVisibility(View.VISIBLE);
        
        // Start background query to load sessions
        mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);
        mHandler.startQuery(QuotesQuery._TOKEN, Quotes.CONTENT_URI, QuotesQuery.PROJECTION);
        progressDialog = CustomProgressDialog.show(WatchlistActivity.this, null, null);
        
        icForex = (ImageView) findViewById(R.id.icForex);
        icCommodities = (ImageView) findViewById(R.id.icCommodities);
        icStocks = (ImageView) findViewById(R.id.icStocks);
        icHeld = (ImageView) findViewById(R.id.icHeld);
        icActive = (ImageView) findViewById(R.id.icActive);
        icAllItems = (ImageView) findViewById(R.id.icAllItems);
    }

    /** {@inheritDoc} */
    public void onQueryComplete(int token, Object cookie, Cursor cursor) {
    	if(token == QuotesQuery._TOKEN) {
    		if(progressDialog != null) progressDialog.dismiss();
    		if(mAdapter != null && cursor != null) {
		    	startManagingCursor(cursor);
		        mAdapter.changeCursor(cursor);
		
		        TextView empty = (TextView) findViewById(android.R.id.empty);
		        if(empty != null) {
		        	if(cursor.getCount()<=0) {
	        			empty.setText(getResources().getString(R.string.search_not_found));
	        			return;
		        	}
		        	empty.setText(null);
		        }
		        System.gc();
	        }
	    	// Start search suggest query to return previous search fitlers
	    	// mHandler.startQuery(SearchSuggestQuery._TOKEN, SearchSuggest.CONTENT_URI, SearchSuggestQuery.PROJECTION);
	    	
	    	if(searchAdapter == null && cursor != null) {
				int count = cursor.getCount();
		    	if(count > 0) {
					String[] array = new String[count];
					int counter = 0;
					while(cursor.moveToNext()) {
		            	array[counter++] = cursor.getString(QuotesQuery.SYMBOL);
					}
					searchAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, array);
				    edtSearch.setAdapter(searchAdapter);
				    edtSearch.setOnItemClickListener(new OnItemClickListener() { 
				        @Override
				        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				        	onSearch(arg1);
				        }
				    });
		    	}
		    	cursor.moveToFirst();
	    	}
	    	
	    	// Update timestamp
	        TextView timestampValue = (TextView) findViewById(R.id.timestampValue);
	        timestampValue.setText(new SimpleDateFormat("d/MM/yy HH:mm").format(new Date()));

    	/*} else {
    		if(cursor != null) {
				int count = cursor.getCount();
		    	if(count > 0) {
					String[] array = new String[count];
					int counter = 0;
					while(cursor.moveToNext()) {
		            	array[counter++] = cursor.getString(SearchSuggestQuery.TEXT);
					}
					searchAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, array);
			        edtSearch.setAdapter(searchAdapter);
		    	}
			}*/    		
    	}
    }

    /**
     * {@link CursorAdapter} that renders a {@link SessionsQuery}.
     */
    private class WatchlistAdapter extends CursorAdapter implements SectionIndexer {
    	AlphabetIndexer alphaIndexer;
    	
    	public WatchlistAdapter(Context context) {
            super(context, null);
            alphaIndexer=new AlphabetIndexer(null, QuotesQuery.SYMBOL, " ABCDEFGHIJKLMNOPQRSTUVWXYZ");
        }

        /** {@inheritDoc} */
        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            alphaIndexer.setCursor(cursor);
        	return getLayoutInflater().inflate(R.layout.list_item_quote, parent, false);
        }

        /** {@inheritDoc} */
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            final TextView symbol = (TextView) view.findViewById(R.id.symbol);
            final TextView name = (TextView) view.findViewById(R.id.name);
            final TextView price = (TextView) view.findViewById(R.id.price);
            final ImageView icChange = (ImageView) view.findViewById(R.id.icChange);
    		final TextView change = (TextView) view.findViewById(R.id.change);
            final LinearLayout sRoot = (LinearLayout) view.findViewById(R.id.sRoot);
            final TextView signal = (TextView) view.findViewById(R.id.signal);
            //final TextView actionLevel = (TextView) view.findViewById(R.id.actionLevel);
            final TextView profitLoss = (TextView) view.findViewById(R.id.profitLoss);
            final ImageView icEmptySignal = (ImageView) view.findViewById(R.id.icEmptySignal);
    		
            // Draw symbol
            SpannableString content = new SpannableString(cursor.getString(QuotesQuery.SYMBOL));
            content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
            symbol.setText(content);
            
            // Draw name
            name.setText(cursor.getString(QuotesQuery.NAME));
            
            // Draw price
            price.setText("" + cursor.getDouble(QuotesQuery.PRICE));
            
            // Draw change 
            icChange.setImageDrawable(null);
            change.setTextColor(getResources().getColor(R.color.grey));
            
            String changeValue = cursor.getString(QuotesQuery.CHANGE); 
            if(!TextUtils.isEmpty(changeValue)) {
            	if(changeValue.indexOf("+") >= 0) {
            		changeValue = changeValue.replace("+", "");
            		change.setTextColor(getResources().getColor(R.color.green));
            		icChange.setImageDrawable(ETApplication.getInstance().getArrowUpDrawable());
            	} else if(changeValue.indexOf("-") >= 0) {
            		changeValue = changeValue.replace("-", "");
            		change.setTextColor(getResources().getColor(R.color.red));
            		icChange.setImageDrawable(ETApplication.getInstance().getArrowDownDrawable());
            	}
            }
            change.setText(changeValue);
            
            // Draw strategy
            String strategy = cursor.getString(QuotesQuery.STRATEGY);
            if("S".equals(strategy)) {
        		sRoot.setVisibility(View.VISIBLE);
        		icEmptySignal.setVisibility(View.GONE);
            	sRoot.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_red));
        		signal.setText(getResources().getString(R.string.sell));
                profitLoss.setText("10");
            } else if("S?".equals(strategy)) {
        		sRoot.setVisibility(View.VISIBLE);
        		icEmptySignal.setVisibility(View.GONE);
        		sRoot.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_red));
        		signal.setText(getResources().getString(R.string.watch));
                profitLoss.setText("10");
            } else if("L".equals(strategy)) {
        		sRoot.setVisibility(View.VISIBLE);
        		icEmptySignal.setVisibility(View.GONE);
        		sRoot.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_green));
        		signal.setText(getResources().getString(R.string.buy));
                profitLoss.setText("10");
            } else if("L?".equals(strategy)) {
        		sRoot.setVisibility(View.VISIBLE);
        		icEmptySignal.setVisibility(View.GONE);
                sRoot.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_green));
        		signal.setText(getResources().getString(R.string.watch));
                profitLoss.setText("10");
            }  else {
        		sRoot.setVisibility(View.GONE);
        		icEmptySignal.setVisibility(View.VISIBLE);
                signal.setText("");
                profitLoss.setText("");
            }
            
        }
    
		@Override
		public int getPositionForSection(int section) {
			try {
				return alphaIndexer.getPositionForSection(section); //use the indexer
			} catch(IllegalStateException e) {
				Log.e(TAG, e.toString());
			}
			return 0;
		}

		@Override
		public int getSectionForPosition(int position) {
			try {
				return alphaIndexer.getSectionForPosition(position); //use the indexer
			} catch(IllegalStateException e) {
				Log.e(TAG, e.toString());
			}
			return 0;
		}

		@Override
		public Object[] getSections() {
			try {
				return alphaIndexer.getSections(); //use the indexer
			} catch(IllegalStateException e) {
				Log.e(TAG, e.toString());
			}
			return null;
		}
    }
    
    /** Handle "refresh" action. Prices for all displayed items will be updated. */
    public void onRefresh(View v) {
    	if(!TextUtils.isEmpty(filter)) {
	   		 mHandler.startQuery(QuotesQuery._TOKEN, Quotes.buildSearchUri(filter), QuotesQuery.PROJECTION);
		} else {
			 mHandler.startQuery(QuotesQuery._TOKEN, Quotes.CONTENT_URI, QuotesQuery.PROJECTION);
		}
    }
    
    /** Handle "search" action. Searches for entry in database. */
    public void onSearch(View v) {
    	String value = edtSearch.getText().toString();
    	if(!TextUtils.isEmpty(value) && value.trim().length() > 0) {
    		 filter = value.toUpperCase();
    		 // Save search filter to search suggest table
    		 //ContentValues values = new ContentValues();
    		 //values.put(SearchManager.SUGGEST_COLUMN_TEXT_1, filter);
    		 //mHandler.startInsert(SearchSuggest.CONTENT_URI, values);
    		 
    		 // Start query, using our filter
    		 mHandler.startQuery(QuotesQuery._TOKEN, Quotes.buildSearchUri(filter), QuotesQuery.PROJECTION);
    	} else {
    		filter = null;
    		mHandler.startQuery(QuotesQuery._TOKEN, Quotes.CONTENT_URI, QuotesQuery.PROJECTION);
    	}
    	// Hide soft keyboard
 		try {
    		InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE); 
    		inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		} catch(Exception e) { }

		resetFilterIcons();
    }
    
    /** Handle "synchronize" action. Causes program data to be synchronized. */
    public void onSync(View v) {
    	
    }
    
    /** Handle "Forex" filter. */
    public void onForex(View v) {
    	filter="forex";
    	mHandler.startQuery(QuotesQuery._TOKEN, Quotes.buildSearchUri(filter), QuotesQuery.PROJECTION);
    	resetFilterIcons();
    	icForex.setImageDrawable(getResources().getDrawable(R.drawable.ic_forex_alt));
    }
    
    /** Handle "Commodities" filter. */
    public void onCommodities(View v) {
    	filter="commodity";
    	mHandler.startQuery(QuotesQuery._TOKEN, Quotes.buildSearchUri(filter), QuotesQuery.PROJECTION);
    	resetFilterIcons();
    	icCommodities.setImageDrawable(getResources().getDrawable(R.drawable.ic_commodities_alt));
    }

    /** Handle "Stocks" filter. */
    public void onStocks(View v) {
    	filter="stock";
    	mHandler.startQuery(QuotesQuery._TOKEN, Quotes.buildSearchUri(filter), QuotesQuery.PROJECTION);
    	resetFilterIcons();
    	icStocks.setImageDrawable(getResources().getDrawable(R.drawable.ic_stocks_alt));
    }

    /** Handle "Active" filter. */
    public void onActive(View v) {
    	filter="active";
    	mHandler.startQuery(QuotesQuery._TOKEN, Quotes.buildSearchUri(filter), QuotesQuery.PROJECTION);
    	resetFilterIcons();
    	icActive.setImageDrawable(getResources().getDrawable(R.drawable.ic_active_alt));
    }

    /** Handle "Held" filter. */
    public void onHeld(View v) {
    	filter="held";
    	mHandler.startQuery(QuotesQuery._TOKEN, Quotes.buildSearchUri(filter), QuotesQuery.PROJECTION);
    	resetFilterIcons();
    	icHeld.setImageDrawable(getResources().getDrawable(R.drawable.ic_held_alt));
    }

    /** Handle "All items" filter. */
    public void onAllItems(View v) {
		filter = null;
		mHandler.startQuery(QuotesQuery._TOKEN, Quotes.CONTENT_URI, QuotesQuery.PROJECTION);
    	resetFilterIcons();
    	icAllItems.setImageDrawable(getResources().getDrawable(R.drawable.ic_allitems_alt));
    }

    @Override
    protected void onDestroy() {
    	super.onDestroy();
        //mAdapter.changeCursor(null);
        //mAdapter = null;
        //mHandler = null;
        //filter = null;
        //edtSearch = null;
        //searchAdapter = null;
        progressDialog = null;
    }
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu_main, menu);
        return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent = null;
		switch (item.getItemId()) {
		    case R.id.help:
		    	intent = new Intent(WatchlistActivity.this, HelpActivity.class);
		        startActivity(intent);
		    	return true;
		    case R.id.settings:
		    	intent = new Intent(WatchlistActivity.this, SettingsActivity.class);
		        startActivity(intent);
		    	return true;
		    case R.id.info:
		    	intent = new Intent(WatchlistActivity.this, InfoActivity.class);
		        startActivity(intent);
		    	return true;
		    case R.id.notifications:
		    	intent = new Intent(WatchlistActivity.this, NotifyActivity.class);
		        startActivity(intent);
		    	return true;
		    case R.id.website:
		    	onWebLinkClick();
		    	return true;
		    case R.id.update:
		    	return true;
		    default:
		    	return true;
	    }
	}
	
	
	// PRIVATE METHODS
	
	/** Handle "web link" action. */
	private void onWebLinkClick() {
		startActivity(new Intent(Intent.ACTION_VIEW , Uri.parse(Keys.VISIT_URL)));
	}
	
    /** {@link Quotes} query parameters. */
    private interface QuotesQuery {
    	int _TOKEN = 0x1;
        String[] PROJECTION = {
        		Tables.QUOTES + "." + BaseColumns._ID,
                Tables.QUOTES + "." + Quotes.SYMBOL,
                Tables.QUOTES + "." + Quotes.PRICE,
                Tables.QUOTES + "." + Quotes.CHANGE,
                Tables.DATA + "." + Data.STRATEGY,
                Tables.DATA + "." + Data.NAME
        };
        int SYMBOL = 1;
        int PRICE = 2;
        int CHANGE = 3;
        int STRATEGY = 4;
        int NAME = 5;
    }
    
    /*private interface SearchSuggestQuery {
    	int _TOKEN = 0x2;
        String[] PROJECTION = {
        		SearchManager.SUGGEST_COLUMN_TEXT_1
        };
        int TEXT = 1;
    }*/
    
    private void resetFilterIcons() {
    	icForex.setImageDrawable(getResources().getDrawable(R.drawable.ic_forex_default));
    	icCommodities.setImageDrawable(getResources().getDrawable(R.drawable.ic_commodities_default));
    	icStocks.setImageDrawable(getResources().getDrawable(R.drawable.ic_stocks_default));
    	icHeld.setImageDrawable(getResources().getDrawable(R.drawable.ic_held_default));
    	icActive.setImageDrawable(getResources().getDrawable(R.drawable.ic_active_default));
    	icAllItems.setImageDrawable(getResources().getDrawable(R.drawable.ic_allitems_default));
    }

	
}
